package com.hopu.springmvc.interceptor;

import com.hopu.springmvc.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录验证拦截器
 */
public class UserLoginInterceptor implements HandlerInterceptor {

    /**
     * 前置处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从Session中获得User对象
        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            //强制跳转到登录页面
            response.sendRedirect("/page/login");
            //false代表拦截，true代表不拦截
            return false;
        }
        //false代表拦截，true代表不拦截
        return true;
    }

    /**
     * 后置处理
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求和响应完成后操作
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
